package org.biogroovy.search.clinicaltrials

import org.biogroovy.io.clinicaltrials.ClinicalTrialReader;
import org.biogroovy.models.ClinicalTrial
import org.biogroovy.models.MeshHeading
import org.biogroovy.search.AbstractSearchEngine
import org.biogroovy.search.IResultBuilder
import org.biogroovy.search.SearchException
import org.biogroovy.search.SearchParam
import org.biogroovy.search.SearchResult


class ClinicalTrialsSearchEngine extends AbstractSearchEngine<SearchResult> {
	
	private static final String NAME = "ClinicalTrials.gov";
	private static final String SEARCH_URL = "http://clinicaltrials.gov/search";
	

	@Override
	public String getName() {
		return NAME;
	}

	@Override
	public String getURLTemplate() {
		return SEARCH_URL;
	}

	@Override
	public List<SearchResult> doSearch(Map<String, String> parameters)
			throws SearchException {
		List<SearchResult> results = new ArrayList<>();	
		
		//TODO: finish me
		
		def root = null;
		ClinicalTrialReader reader = new ClinicalTrialReader();
		reader.parseList(this, SEARCH_URL)
			
		return null;
	}

	@Override
	protected void initSearchParams() {
		SearchParam term = new SearchParam(name:'term', isTerm: true, isRequired: true,isEditable: true);
		SearchParam displayXML = new SearchParam(name:'displayxml', isSubTerm:true, isRequired: true);
		getSearchParameters().addAll(term, displayXML);
		
	}
	
	class ClinicalTrialResultBuilder implements IResultBuilder<ClinicalTrial>{

		@Override
		public SearchResult<ClinicalTrial> convert(ClinicalTrial trial) {
			SearchResult<ClinicalTrial> result = new SearchResult([title: trial.briefTitle, description:trial.briefSummary]);
			result.url = trial.clinicalTrialUri;
			result.accession = trial.clinicalTrialId;
			result.tags = new ArrayList();
			
			trial.tags.each{String tag ->
				result.tags.add(tag);
			}
			trial.meshTerms.each{MeshHeading term ->
				result.tags.add(term.descriptorName);
			}
			
			result.setResult(trial);
			return result;
		}
		
	}

}
